package com.example.util;

/**
 * @author long
 * @date 2024/12/30 13:28
 */
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
 * @description
 */
@Slf4j
@Component
public class RedisUtils {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 设置值，不带超时时间
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        log.info("set key:{} value:{}", key, value);
        stringRedisTemplate.opsForValue().set(key,value);
    }

    /**
     * 设置值，带超时时间
     * @param key
     * @param value
     * @param expireTime
     */
    public void set(String key, String value, int expireTime) {
        log.info("set key:{} value:{} expireTime:{}", key, value, expireTime);
        stringRedisTemplate.opsForValue().set(key,value, expireTime,TimeUnit.SECONDS);
    }

    /**
     * 取值
     * @param key
     * @return
     */
    public String get(String key) {
        log.info("get key:{}", key);
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 删除key
     * @param key
     * @return
     */
    public Boolean del(String key) {
        if (exists(key)) {
            return stringRedisTemplate.delete(key);
        } else {
            log.error("del key:{}", key+" 不存在");
            return false;
        }
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    public Boolean exists(String key) {
        Boolean exists = stringRedisTemplate.hasKey(key);
        log.info("exists key:{} hasKey:{}", key, exists);
        return exists;
    }

}
